<?PHP
/*
    Registration/Login script from HTML Form Guide
    V1.0

    This program is free software published under the
    terms of the GNU Lesser General Public License.
    http://www.gnu.org/copyleft/lesser.html
    

This program is distributed in the hope that it will
be useful - WITHOUT ANY WARRANTY; without even the
implied warranty of MERCHANTABILITY or FITNESS FOR A
PARTICULAR PURPOSE.

For updates, please visit:
http://www.html-form-guide.com/php-form/php-registration-form.html
http://www.html-form-guide.com/php-form/php-login-form.html

*/
require_once("class.phpmailer.php");
require_once("formvalidator.php");

class FGMembersite
{
    var $admin_email;
    var $from_address;
    
    var $username;
    var $pwd;
    var $database;
    var $tablename;
    var $connection;
    var $rand_key;
    
    var $error_message;
    
	// --- ABBR --- TE
	//----- TE = Trivia Extension --------
	var $questiontable;
	var $answertable;
	
	//smtp vars
	
	var $smtpHost;
	
	/**
	 * Sets the default SMTP server port.
	 * @var int
	 */
	var $smtpPort;
	
	/**
	 * Sets the SMTP HELO of the message (Default is $Hostname).
	 * @var string
	 */
	var $smtpHelo;
	
	/**
	 * Sets connection prefix. Options are "", "ssl" or "tls"
	 * @var string
	 */
	var $SmtpSecur;
	
	/**
	 * Sets SMTP authentication. Utilizes the Username and Password variables.
	 * @var bool
	 */
	var $SmtpAuth;
	
	/**
	 * Sets SMTP username.
	 * @var string
	 */
	var $smtpUsername;
	
	/**
	 * Sets SMTP password.
	 * @var string
	 */
	var $smtpPassword;
	
	/**
	 *  Sets SMTP auth type. Options are LOGIN | PLAIN | NTLM | CRAM-MD5 (default LOGIN)
	 *  @var string
	 */
	var $smtpAuthType;
	
	/**
	 *  Sets SMTP realm.
	 *  @var string
	 */
	var $smtpRealm;
	
	// mail vars
	
	//welcome user vars
	
	var $wuserMailSubject;
	var $wuserFromAdd;
    var $wuserGreetingUser; 
    var $wuserBody; 
    var $wuserCharset;
    // 	 * Email priority (1 = High, 3 = Normal, 5 = low).
    var $wuserPriority;
    //welcome  confirmation user vars
    var $wconfuMailSubject;
    var $wconfuFromAdd;
    var $wconfuBody;
    var $wconfuCharset;
    // 	 * Email priority (1 = High, 3 = Normal, 5 = low).
    var $wconfuPriority;
    //admin on registration  vars
    
    var $aorserMailSubject;
    var $aorserFromAdd;
    var $aorBody;
    var $aorCharset;
    var $aorTOAdd;
    // 	 * Email priority (1 = High, 3 = Normal, 5 = low).
    var $aorPriority;

    //admin Intimation Email  vars
      
    var $aieserMailSubject;
    var $aieserFromAdd;
    var $aieBody;
    var $aieCharset;
    var $aieTOAdd;
    // 	 * Email priority (1 = High, 3 = Normal, 5 = low).
    var $aeiPriority;
    
    //send new password
    
    var $snpMailSubject;
    var $snpFromAdd;
    var $snpBody;
    var $snpCharset;
    // 	 * Email priority (1 = High, 3 = Normal, 5 = low).
    var $snpPriority;
    
    //send new link password
    
    var $slpMailSubject;
    var $slpFromAdd;
    var $slpBody;
    var $slpCharset;
    // 	 * Email priority (1 = High, 3 = Normal, 5 = low).
    var $slpPriority;
	
	
	//  * Ranking on top n
	var $topn;
	
// 	/**

// 	 * @var int
// 	 */
// 	var $emailPriority;
	
// 	/**
// 	 * Sets the CharSet of the message.
// 	 * @var string
// 	 */
// 	var $emailCharSet;
	
// 	/**
// 	 * Sets the Content-type of the message.
// 	 * @var string
// 	 */
// 	var $emailContentType;
	
// 	/**
// 	 * Sets the Encoding of the message. Options for this are
// 	 *  "8bit", "7bit", "binary", "base64", and "quoted-printable".
// 	 * @var string
// 	 */
// 	var $emailEncoding;
	
// 	/**
// 	 * Sets the From email address for the message.
// 	 * @var string
// 	 */
// 	var $emailFrom;
	
// 	/**
// 	 * Sets the From name of the message.
// 	 * @var string
// 	 */
// 	var $emailFromName;
	
	
	
    //-----Initialization -------
    function FGMembersite()
    {
        $this->sitename = 'localhost';
        $this->rand_key = '0iQx5oBk66oVZep';
    }
    
    function InitDB($host,$uname,$pwd,$database,$tablename)
    {
        $this->db_host  = $host;
        $this->username = $uname;
        $this->pwd  = $pwd;
        $this->database  = $database;
        $this->tablename = $tablename;
        
		// --- ABBR --- TE
		$this->questiontable = 'question';
		$this->answertable = 'answer';
		
    }
    
	function SetTopn ($number)
	{
		$this->topn = $number;
	}
	
	function SetAdminEmail($email)
    {
        $this->admin_email = $email;
    }
    
    function SetWebsiteName($sitename)
    {
        $this->sitename = $sitename;
    }
    
    function SetRandomKey($key)
    {
        $this->rand_key = $key;
    }
    
    //-------Main Operations ----------------------
    function RegisterUser()
    {
        if(!isset($_POST['submitted']))
        {
           return false;
        }
        
        $formvars = array();
        
        if(!$this->ValidateRegistrationSubmission())
        {
            return false;
        }
        
        $this->CollectRegistrationSubmission($formvars);
        
        if(!$this->SaveToDatabase($formvars))
        {
            return false;
        }
        
        if(!$this->SendUserConfirmationEmail($formvars))
        {
            return false;
        }

        $this->SendAdminIntimationEmail($formvars);
        
        return true;
    }

    function ConfirmUser()
    {
        if(empty($_GET['code'])||strlen($_GET['code'])<=10)
        {
            $this->HandleError("Please provide the confirm code");
            return false;
        }
        $user_rec = array();
        if(!$this->UpdateDBRecForConfirmation($user_rec))
        {
            return false;
        }
        
        $this->SendUserWelcomeEmail($user_rec);
        
        $this->SendAdminIntimationOnRegComplete($user_rec);
        
        return true;
    }    
    
    function Login()
    {
        if(empty($_POST['username']))
        {
            $this->HandleError("UserName is empty!");
            return false;
        }
        
        if(empty($_POST['password']))
        {
            $this->HandleError("Password is empty!");
            return false;
        }
        
        $username = trim($_POST['username']);
        $password = trim($_POST['password']);
        
        if(!isset($_SESSION)){ session_start(); }
        if(!$this->CheckLoginInDB($username,$password))
        {
            return false;
        }
        
        $_SESSION[$this->GetLoginSessionVar()] = $username;
        
        return true;
    }
    
    function CheckLogin()
    {
         if(!isset($_SESSION)){ session_start(); }

         $sessionvar = $this->GetLoginSessionVar();
         
         if(empty($_SESSION[$sessionvar]))
         {
            return false;
         }
         return true;
    }
    
    function UserFullName()
    {
        return isset($_SESSION['name_of_user'])?$_SESSION['name_of_user']:'';
    }

    function UserId()
    {
        return isset($_SESSION['userid'])?$_SESSION['userid']: -1;
    }
        
    function UserEmail()
    {
        return isset($_SESSION['email_of_user'])?$_SESSION['email_of_user']:'';
    }
    
    function LogOut()
    {
        session_start();
        
        $sessionvar = $this->GetLoginSessionVar();
        
        $_SESSION[$sessionvar]=NULL;
        
        unset($_SESSION[$sessionvar]);
    }
    
    function EmailResetPasswordLink()
    {
        if(empty($_POST['email']))
        {
            $this->HandleError("Email is empty!");
            return false;
        }
        $user_rec = array();
        if(false === $this->GetUserFromEmail($_POST['email'], $user_rec))
        {
            return false;
        }
        if(false === $this->SendResetPasswordLink($user_rec))
        {
            return false;
        }
        return true;
    }
    
    function ResetPassword()
    {
        if(empty($_GET['email']))
        {
            $this->HandleError("Email is empty!");
            return false;
        }
        if(empty($_GET['code']))
        {
            $this->HandleError("reset code is empty!");
            return false;
        }
        $email = trim($_GET['email']);
        $code = trim($_GET['code']);
        
        if($this->GetResetPasswordCode($email) != $code)
        {
            $this->HandleError("Bad reset code!");
            return false;
        }
        
        $user_rec = array();
        if(!$this->GetUserFromEmail($email,$user_rec))
        {
            return false;
        }
        
        $new_password = $this->ResetUserPasswordInDB($user_rec);
        if(false === $new_password || empty($new_password))
        {
            $this->HandleError("Error updating new password");
            return false;
        }
        
        if(false == $this->SendNewPassword($user_rec,$new_password))
        {
            $this->HandleError("Error sending new password");
            return false;
        }
        return true;
    }
    
    function ChangePassword()
    {
        if(!$this->CheckLogin())
        {
            $this->HandleError("Not logged in!");
            return false;
        }
        
        if(empty($_POST['oldpwd']))
        {
            $this->HandleError("Old password is empty!");
            return false;
        }
        if(empty($_POST['newpwd']))
        {
            $this->HandleError("New password is empty!");
            return false;
        }
        
        $user_rec = array();
        if(!$this->GetUserFromEmail($this->UserEmail(),$user_rec))
        {
            return false;
        }
        
        $pwd = trim($_POST['oldpwd']);
        
        if($user_rec['password'] != md5($pwd))
        {
            $this->HandleError("The old password does not match!");
            return false;
        }
        $newpwd = trim($_POST['newpwd']);
        
        if(!$this->ChangePasswordInDB($user_rec, $newpwd))
        {
            return false;
        }
        return true;
    }
    
    //-------Public Helper functions -------------
    function GetSelfScript()
    {
        return htmlentities($_SERVER['PHP_SELF']);
    }    
    
    function SafeDisplay($value_name)
    {
        if(empty($_POST[$value_name]))
        {
            return'';
        }
        return htmlentities($_POST[$value_name]);
    }
    
    function RedirectToURL($url)
    {
        header("Location: $url");
        exit;
    }
    
    function GetSpamTrapInputName()
    {
        return 'sp'.md5('KHGdnbvsgst'.$this->rand_key);
    }
    
    function GetErrorMessage()
    {
        if(empty($this->error_message))
        {
            return '';
        }
        $errormsg = nl2br(htmlentities($this->error_message));
        return $errormsg;
    }    
    //-------Private Helper functions-----------
    
    function HandleError($err)
    {
        $this->error_message .= $err."\r\n";
    }
    
    function HandleDBError($err)
    {
        $this->HandleError($err."\r\n mysqlerror:".mysql_error());
    }
    
    function GetFromAddress()
    {
        if(!empty($this->from_address))
        {
            return $this->from_address;
        }

        $host = $_SERVER['SERVER_NAME'];

        $from ="abaranya@cantv.net";
        return $from;
    } 
    
    function GetLoginSessionVar()
    {
        $retvar = md5($this->rand_key);
        $retvar = 'usr_'.substr($retvar,0,10);
        return $retvar;
    }
    
    function CheckLoginInDB($username,$password)
    {
        if(!$this->DBLogin())
        {
            $this->HandleError("Database login failed!");
            return false;
        }          
        $username = $this->SanitizeForSQL($username);
        $pwdmd5 = md5($password);
      	$qry = "Select id_user, name, email from $this->tablename where username='$username' and password='$pwdmd5' and confirmcode='y'";
        
        $result = mysql_query($qry,$this->connection);
        
        if(!$result || mysql_num_rows($result) <= 0)
        {
            $this->HandleError("Error logging in. The username or password does not match");
            return false;
        }
        
        $row = mysql_fetch_assoc($result);
        
        $_SESSION['userid'] = $row['id_user'];
        $_SESSION['name_of_user']  = $row['name'];
        $_SESSION['email_of_user'] = $row['email'];
        
        return true;
    }

   	function Answer($user, $question, $answer, $grade)
	{
        if(!$this->DBLogin())
        {
            $this->HandleError("Database login failed!");
            return false;
        }   

		$qry = "insert into answer (id_user, id_question, selection, grade) values ($user, $question, $answer, $grade) ";

        $result = mysql_query($qry,$this->connection);
		
        if(!$result)
        {
			$error_message = mysql_error();
			$this->HandleDBError("Error fetching question[$error_message]. $qry with result '$query_no'");
			$_SESSION['current_question'] = -1;
            return false;
        }
		
		$_SESSION['current_question'] = 0;
		return true;
	}
	
	function FetchQuestion()
	{
        if(!$this->DBLogin())
        {
            $this->HandleError("Database login failed!");
            return false;
        }   

		$userid = $this->UserId();
		
		$qry = "select IFNULL(min(id_question),0) as id_question from question where id_question not in (Select IFNULL(id_question,-2) from answer where id_user = '$userid' )";
//		$qry = "select id_question, id_user from wrongtable where id_user = $userid ";
        
        $result = mysql_query($qry,$this->connection);
		
        if(!$result)
        {
			$error_message = mysql_error();
			$this->HandleDBError("Error fetching question[$error_message]. $qry with result '$query_no'");
			$_SESSION['current_question'] = -1;
            return false;
        }
        
  		$_SESSION['current_question'] = mysql_result($result,0);
		$question = $_SESSION['current_question'];
		
		$qry = "select question, week, options, option1, option2, option3, option4, option5, option6, option7, option8, correct from question where id_question =  $question ";

        $result = mysql_query($qry,$this->connection);
		
        if(!$result)
        {
			$error_message = mysql_error();
			$this->HandleDBError("Error fetching question[$error_message]. $qry with result '$query_no'");
			$_SESSION['current_question'] = -1;
            return false;
        }
		
        $row = mysql_fetch_assoc($result);
  
		$_SESSION['question_text']  = $row['question'];
		$_SESSION['question_options']  = $row['options'];
		$_SESSION['question_option1']  = $row['option1'];
		$_SESSION['question_option2']  = $row['option2'];
		$_SESSION['question_option3']  = $row['option3'];
		$_SESSION['question_option4']  = $row['option4'];
		$_SESSION['question_option5']  = $row['option5'];
		$_SESSION['question_option6']  = $row['option6'];
		$_SESSION['question_option7']  = $row['option7'];
		$_SESSION['question_option8']  = $row['option8'];
		$_SESSION['question_correct']  = $row['correct'];

		return true;
	}
	
	function FetchRanking() 
	{
        if(!$this->DBLogin())
        {
            $this->HandleError("Database login failed!");
            return false;
        }   
		
		$qry = "SELECT ans.id_user as id, name, sum(grade) as points FROM `answer` ans, fgusers3 usr where ans.id_user = usr.id_user group by ans.id_user order by points DESC";
//		$qry = "select id_question, id_user from wrongtable where id_user = $userid ";

        $result = mysql_query($qry,$this->connection);
        
		$rows = mysql_num_rows($result);
		
        if(!$result || mysql_num_rows($result) <= 0)
        {
            $this->HandleError("La información de ranking no está disponible");
            return false;
        }
		
		for($i = 1; $i <= $rows; $i++) {

	        $row = mysql_fetch_assoc($result);
	
			if (isset($_SESSION['ranking'.$i])){
    			$ranking = $_SESSION['ranking'.$i];
			}else{	
    			$ranking = array();	
    			$_SESSION['ranking'.$i]=$ranking;
			}
	
			$_SESSION['ranking'.$i] ['id']= $row['id'];
			$_SESSION['ranking'.$i] ['name']= $row['name'];
			$_SESSION['ranking'.$i] ['points']= $row['points'];

		}

		$_SESSION['ranking_rows'] = $rows;
		
		return true;
	}
		
			

	
    function UpdateDBRecForConfirmation(&$user_rec)
    {
        if(!$this->DBLogin())
        {
            $this->HandleError("Database login failed!");
            return false;
        }   
        $confirmcode = $this->SanitizeForSQL($_GET['code']);
        
        $result = mysql_query("Select name, email from $this->tablename where confirmcode='$confirmcode'",$this->connection);   
        if(!$result || mysql_num_rows($result) <= 0)
        {
            $this->HandleError("Wrong confirm code.");
            return false;
        }
        $row = mysql_fetch_assoc($result);
        $user_rec['name'] = $row['name'];
        $user_rec['email']= $row['email'];
        
        $qry = "Update $this->tablename Set confirmcode='y' Where  confirmcode='$confirmcode'";
        
        if(!mysql_query( $qry ,$this->connection))
        {
            $this->HandleDBError("Error inserting data to the table\nquery:$qry");
            return false;
        }      
        return true;
    }
    
    function ResetUserPasswordInDB($user_rec)
    {
        $new_password = substr(md5(uniqid()),0,10);
        
        if(false == $this->ChangePasswordInDB($user_rec,$new_password))
        {
            return false;
        }
        return $new_password;
    }
    
    function ChangePasswordInDB($user_rec, $newpwd)
    {
        $newpwd = $this->SanitizeForSQL($newpwd);
        
        $qry = "Update $this->tablename Set password='".md5($newpwd)."' Where  id_user=".$user_rec['id_user']."";
        
        if(!mysql_query( $qry ,$this->connection))
        {
            $this->HandleDBError("Error updating the password \nquery:$qry");
            return false;
        }     
        return true;
    }
    
    function GetUserFromEmail($email,&$user_rec)
    {
        if(!$this->DBLogin())
        {
            $this->HandleError("Database login failed!");
            return false;
        }   
        $email = $this->SanitizeForSQL($email);
        
        $result = mysql_query("Select * from $this->tablename where email='$email'",$this->connection);  

        if(!$result || mysql_num_rows($result) <= 0)
        {
            $this->HandleError("There is no user with email: $email");
            return false;
        }
        $user_rec = mysql_fetch_assoc($result);

        
        return true;
    }
    
    function SendUserWelcomeEmail(&$user_rec)
    {
//        $mailer = new PHPMailer($this,false);
    		$mailer = $this->setMailer();
//         $mailer->CharSet = 'utf-8';
        
//         $mailer->AddAddress($user_rec['email'],$user_rec['name']);
        
//         $mailer->Subject = "Welcome to ".$this->sitename;

//         $mailer->From = $this->GetFromAddress();        
        
//         $mailer->Body ="Hello ".$user_rec['name']."\r\n\r\n".
//         "Welcome! Your registration  with ".$this->sitename." is completed.\r\n".
//         "\r\n".
//         "Regards,\r\n".
//         "Webmaster\r\n".
//         $this->sitename;
		   $completeBody = preg_replace("%\\$\\[user\\]%", $user_rec['name'], $this->wuserGreetingUser).$this->wuserBody;
           $mailer->CharSet = $this->wuserCharset;
           $mailer->AddAddress($user_rec['email'],$user_rec['name']);
           $mailer->Subject = $this->wuserMailSubject;
           $mailer->From = $this->wuserFromAdd;
           $mailer->Body = $completeBody;
           $mailer->Priority = $this->wuserPriority;

        if(!$mailer->Send())
        {
            $this->HandleError("Failed sending user welcome email.");
            return false;
        }
        return true;
    }
    
    function SendAdminIntimationOnRegComplete(&$user_rec)
    {
        if(empty($this->admin_email))
        {
            return false;
        }
        $mailer = $this->setMailer();
//         $mailer = new PHPMailer($this,false);
        
//         $mailer->CharSet = 'utf-8';
        
//         $mailer->AddAddress($this->admin_email);
        
//         $mailer->Subject = "Registration Completed: ".$user_rec['name'];

//         $mailer->From = $this->GetFromAddress();         
        
//         $mailer->Body ="A new user registered at ".$this->sitename."\r\n".
//         "Name: ".$user_rec['name']."\r\n".
//         "Email address: ".$user_rec['email']."\r\n";
		$subject =  preg_replace("%\\$\\[user\\]%", $user_rec['name'], $this->aorserMailSubject);
		$body =  preg_replace("%\\$\\[user\\]%", $user_rec['name'], $this->aorBody);
		$body =  preg_replace("%\\$\\[userMail\\]%", $user_rec['email'], $body);
		$mailer->CharSet = $this->aorCharset;
        $mailer->AddAddress($this->aorTOAdd);
        $mailer->Subject = $subject;
        $mailer->From = $this->aorserFromAdd;
        $mailer->Body = $body;
        $mailer->Priority = $this->aorPriority;
        
        if(!$mailer->Send())
        {
            return false;
        }
        return true;
    }
    
    function GetResetPasswordCode($email)
    {
       return substr(md5($email.$this->sitename.$this->rand_key),0,10);
    }
    
    function SendResetPasswordLink($user_rec)
    {
        $email = $user_rec['email'];
        $mailer = $this->setMailer();
       
//         $mailer = new PHPMailer($this,false);
        
//         $mailer->CharSet = 'utf-8';
        
//         $mailer->AddAddress($email,$user_rec['name']);
        
//         $mailer->Subject = "Your reset password request at ".$this->sitename;

//         $mailer->From = $this->GetFromAddress();
        
        $link = $this->GetAbsoluteURLFolder().
                '/resetpwd.php?email='.
                urlencode($email).'&code='.
                urlencode($this->GetResetPasswordCode($email));

//         $mailer->Body ="Hello ".$user_rec['name']."\r\n\r\n".
//         "There was a request to reset your password at ".$this->sitename."\r\n".
//         "Please click the link below to complete the request: \r\n".$link."\r\n".
//         "Regards,\r\n".
//         "Webmaster\r\n".
//         $this->sitename;
		$body = preg_replace("%\\$\\[name\\]%", $user_rec['name'], $this->slpBody);
		$body = preg_replace("%\\$\\[link\\]%", $link, $this->slpBody);
        $mailer->CharSet = $this->slpCharset;
        $mailer->AddAddress($email,$user_rec['name']);
        $mailer->Subject = $this->slpMailSubject;
        $mailer->From = $this->slpFromAdd;
        $mailer->Body = $body;
        $mailer->Priority = $this->slpPriority;
        
        if(!$mailer->Send())
        {
            return false;
        }
        return true;
    }
    
    function SendNewPassword($user_rec, $new_password)
    {
        $email = $user_rec['email'];
        $mailer = $this->setMailer();
        
//        $mailer = new PHPMailer($this,false);
        
//         $mailer->CharSet = 'utf-8';
        
//         $mailer->AddAddress($email,$user_rec['name']);
        
//         $mailer->Subject = "Your new password for ".$this->sitename;

//         $mailer->From = $this->GetFromAddress();
        
//         $mailer->Body ="Hello ".$user_rec['name']."\r\n\r\n".
//         "Your password is reset successfully. ".
//         "Here is your updated login:\r\n".
//         "username:".$user_rec['username']."\r\n".
//         "password:$new_password\r\n".
//         "\r\n".
//         "Login here: ".$this->GetAbsoluteURLFolder()."/login.php\r\n".
//         "\r\n".
//         "Regards,\r\n".
//         "Webmaster\r\n".
//         $this->sitename;
		$body =  preg_replace("%\\$\\[name\\]%",$user_rec['name'], $this->snpBody);
		$body =  preg_replace("%\\$\\[user\\]%",$user_rec['username'], $body);
		$body =  preg_replace("%\\$\\[password\\]%",$new_password, $body);
		$body =  preg_replace("%\\$\\[url\\]%",$this->GetAbsoluteURLFolder()."/login.php\r\n", $body);
       	$mailer->CharSet = $this->snpCharset;
       	$mailer->AddAddress($email,$user_rec['name']);
       	$mailer->Subject = $this->snpMailSubject;
       	$mailer->From = $this->snpFromAdd;
       	$mailer->Body = $body;
       	$mailer->Priority = $this->snpPriority;
       	
        if(!$mailer->Send())
        {
            return false;
        }
        return true;
    }    
    
    function ValidateRegistrationSubmission()
    {
        //This is a hidden input field. Humans won't fill this field.
        if(!empty($_POST[$this->GetSpamTrapInputName()]) )
        {
            //The proper error is not given intentionally
            $this->HandleError("Automated submission prevention: case 2 failed");
            return false;
        }
        
        $validator = new FormValidator();
        $validator->addValidation("name","req","Please fill in Name");
        $validator->addValidation("email","email","The input for Email should be a valid email value");
        $validator->addValidation("email","req","Please fill in Email");
        $validator->addValidation("username","req","Please fill in UserName");
        $validator->addValidation("password","req","Please fill in Password");

        
        if(!$validator->ValidateForm())
        {
            $error='';
            $error_hash = $validator->GetErrors();
            foreach($error_hash as $inpname => $inp_err)
            {
                $error .= $inpname.':'.$inp_err."\n";
            }
            $this->HandleError($error);
            return false;
        }        
        return true;
    }
    
    function CollectRegistrationSubmission(&$formvars)
    {
        $formvars['name'] = $this->Sanitize($_POST['name']);
        $formvars['email'] = $this->Sanitize($_POST['email']);
        $formvars['username'] = $this->Sanitize($_POST['username']);
        $formvars['password'] = $this->Sanitize($_POST['password']);
    }
    
    function SendUserConfirmationEmail(&$formvars)
    {
//         $mailer = new PHPMailer($this,false);
         $mailer = $this->setMailer();
        
//         $mailer->CharSet = 'utf-8';
        
		// --- ABBR TODO:  Setup properly
		
//         $mailer->AddAddress($formvars['email'],$formvars['name']);
 
//         l
//         $mailer->Subject = "Your registration with ".$this->sitename;

//         $mailer->From = $this->GetFromAddress();        
// //        $mailer->From = "abaranya@cantv.net";        
        
//         $confirmcode = $formvars['confirmcode'];
        
//         $confirm_url = $this->GetAbsoluteURLFolder().'/confirmreg.php?code='.$confirmcode;
        
//         $mailer->Body ="Hello ".$formvars['name']."\r\n\r\n".
//         "Thanks for your registration with ".$this->sitename."\r\n".
//         "Please click the link below to confirm your registration.\r\n".
//         "$confirm_url\r\n".
//         "\r\n".
//         "Regards,\r\n".
//         "Webmaster\r\n".
//         $this->sitename;
        $confirmcode = $formvars['confirmcode'];
        $confirm_url = $this->GetAbsoluteURLFolder().'/confirmreg.php?code='.$confirmcode;
        $completeBody = preg_replace("%\\$\\[user\\]%",$formvars['name'],$this->wconfuBody);
        $completeBody=  preg_replace("%\\$\\[confirmUrl\\]%", $confirm_url, $completeBody);
        $mailer->AddAddress($formvars['email'],$formvars['name']);
        $mailer->Subject = $this->wconfuMailSubject;
        $mailer->From = $this->wconfuFromAdd;
        $mailer->Body = $completeBody;
        $mailer->Priority = $this->wconfuPriority;
// 		$mailer->IsSMTP();
// 		$mailer->$mail->SMTPDebug  = 2;  
	
 
        if(!$mailer->Send())
        {
            $this->HandleError("Failed sending registration confirmation email.");
			$this->HandleError($mailer->ErrorInfo);
            return false;
        }
        return true;
    }
    function GetAbsoluteURLFolder()
    {
        $scriptFolder = (isset($_SERVER['HTTPS']) && ($_SERVER['HTTPS'] == 'on')) ? 'https://' : 'http://';
        $scriptFolder .= $_SERVER['HTTP_HOST'];
		$directory = dirname($_SERVER['REQUEST_URI']);
		if ( $directory != '\\' && $directory != '.' )
			$scriptFolder .= $directory;
			
        return $scriptFolder;
    }
    
    function SendAdminIntimationEmail(&$formvars)
    {
        if(empty($this->admin_email))
        {
            return false;
        }
        $mailer = $this->setMailer();
//        $mailer = new PHPMailer($this,false);
        
//         $mailer->CharSet = 'utf-8';
        
//         $mailer->AddAddress($this->admin_email);
        
//         $mailer->Subject = "New registration: ".$formvars['name'];

//         $mailer->From = $this->GetFromAddress();         
        
//         $mailer->Body ="A new user registered at ".$this->sitename."\r\n".
//         "Name: ".$formvars['name']."\r\n".
//         "Email address: ".$formvars['email']."\r\n".
//         "UserName: ".$formvars['username'];
        $subject =  preg_replace("%\\$\\[user\\]%", $formvars['username'], $this->aieserMailSubject);
        $body = preg_replace("%\\$\\[user\\]%", $formvars['username'], $this->aieBody);
        $body = preg_replace("%\\$\\[userMail\\]%",$formvars['email'], $body);
        $body = preg_replace("%\\$\\[name\\]%",$formvars['name'], $body);
        $mailer->CharSet = $this->aieCharset;
       	$mailer->AddAddress($this->aieTOAdd);
       	$mailer->Subject = $subject;
        $mailer->From = $this->aieserFromAdd;
        $mailer->Body = $body;
       
        if(!$mailer->Send())
        {
            return false;
        }
        return true;
    }
    
    function SaveToDatabase(&$formvars)
    {
        if(!$this->DBLogin())
        {
            $this->HandleError("Database login failed!");
            return false;
        }
        if(!$this->Ensuretable())
        {
            return false;
        }
        if(!$this->IsFieldUnique($formvars,'email'))
        {
            $this->HandleError("This email is already registered");
            return false;
        }
        
        if(!$this->IsFieldUnique($formvars,'username'))
        {
            $this->HandleError("This UserName is already used. Please try another username");
            return false;
        }        
        if(!$this->InsertIntoDB($formvars))
        {
            $this->HandleError("Inserting to Database failed!");
            return false;
        }
        return true;
    }
    
    function IsFieldUnique($formvars,$fieldname)
    {
        $field_val = $this->SanitizeForSQL($formvars[$fieldname]);
        $qry = "select username from $this->tablename where $fieldname='".$field_val."'";
        $result = mysql_query($qry,$this->connection);   
        if($result && mysql_num_rows($result) > 0)
        {
            return false;
        }
        return true;
    }
    
    function DBLogin()
    {

        $this->connection = mysql_connect($this->db_host,$this->username,$this->pwd);

        if(!$this->connection)
        {   
            $this->HandleDBError("Database Login failed! Please make sure that the DB login credentials provided are correct");
            return false;
        }
        if(!mysql_select_db($this->database, $this->connection))
        {
            $this->HandleDBError('Failed to select database: '.$this->database.' Please make sure that the database name provided is correct');
            return false;
        }
        if(!mysql_query("SET NAMES 'UTF8'",$this->connection))
        {
            $this->HandleDBError('Error setting utf8 encoding');
            return false;
        }
        return true;
    }    
    
    function Ensuretable()
    {
        $result = mysql_query("SHOW COLUMNS FROM $this->tablename");   
        if(!$result || mysql_num_rows($result) <= 0)
        {
            return $this->CreateTable();
        }
        return true;
    }
    
    function CreateTable()
    {
 		if(!$this->CreateQuizTable())
		{
			$this->HandleDBError("Error creating Quiz Tables");
			return false;
		}
	
        $qry = "Create Table $this->tablename (".
                "id_user INT NOT NULL AUTO_INCREMENT ,".
                "name VARCHAR( 128 ) NOT NULL ,".
                "email VARCHAR( 64 ) NOT NULL ,".
                "phone_number VARCHAR( 16 ) NOT NULL ,".
                "username VARCHAR( 16 ) NOT NULL ,".
                "password VARCHAR( 32 ) NOT NULL ,".
                "confirmcode VARCHAR(32) ,".
                "PRIMARY KEY ( id_user )".
                ")";
                
        if(!mysql_query($qry,$this->connection))
        {
            $this->HandleDBError("Error creating the table \nquery was\n $qry");
            return false;
        }
		
		return true;
		
    }
	
	// --- ABBR --- Extend to create Questions
	function CreateQuizTable()
	{
		
        $qry = "Create Table $this->questiontable (".
                "id_question INT NOT NULL AUTO_INCREMENT ,".
                "question VARCHAR( 256 ) NOT NULL ,".
                "week INT NOT NULL ,".
                "options INT NOT NULL ,".
                "option1 VARCHAR( 128 ) NOT NULL ,".
                "option2 VARCHAR( 128 ) NOT NULL ,".
                "option3 VARCHAR( 128 ) NOT NULL ,".
                "option4 VARCHAR( 128 ) NOT NULL ,".
                "option5 VARCHAR( 128 ) NOT NULL ,".
                "option6 VARCHAR( 128 ) NOT NULL ,".
                "option7 VARCHAR( 128 ) NOT NULL ,".
                "option8 VARCHAR( 128 ) NOT NULL ,".
				"with_optional INT NOT NULL DEFAULT  '0' ,".
                "correct INT NOT NULL ,".
                "PRIMARY KEY ( id_question )".
                ")";
                
        if(!mysql_query($qry,$this->connection))
        {
            $this->HandleDBError("Error creating the table \nquery was\n $qry");
            return false;
        }
		
        $qry = "Create Table $this->answertable (".
                "id_user INT NOT NULL,".
				"id_question INT NOT NULL ,".
                "week INT NOT NULL ,".
                "selection INT NOT NULL ,".
                "grade INT NOT NULL ,".
                "PRIMARY KEY ( id_user, id_question )".
                ")";
                
        if(!mysql_query($qry,$this->connection))
        {
            $this->HandleDBError("Error creating the table \nquery was\n $qry");
            return false;
        }

		return true;

	}
    
    function InsertIntoDB(&$formvars)
    {
    
        $confirmcode = $this->MakeConfirmationMd5($formvars['email']);
        
        $formvars['confirmcode'] = $confirmcode;
        
        $insert_query = 'insert into '.$this->tablename.'(
                name,
                email,
                username,
                password,
                confirmcode
                )
                values
                (
                "' . $this->SanitizeForSQL($formvars['name']) . '",
                "' . $this->SanitizeForSQL($formvars['email']) . '",
                "' . $this->SanitizeForSQL($formvars['username']) . '",
                "' . md5($formvars['password']) . '",
                "' . $confirmcode . '"
                )';      
        if(!mysql_query( $insert_query ,$this->connection))
        {
            $this->HandleDBError("Error inserting data to the table\nquery:$insert_query");
            return false;
        }        
		
		$userid = mysql_insert_id();

        $insert_query = 'insert into '.$this->answertable.'(
                id_user,
				id_question,
                week,
                selection,
                grade
                )
                values
                (
                "' . $userid . '",
                "0",
                "0",
                "0",
                "0"
                )';
				      
        if(!mysql_query( $insert_query ,$this->connection))
        {
            $this->HandleDBError("Error inserting data to the table\nquery:$insert_query");
            return false;
        }        

		return true;
    }
	
    function MakeConfirmationMd5($email)
    {
        $randno1 = rand();
        $randno2 = rand();
        return md5($email.$this->rand_key.$randno1.''.$randno2);
    }
    function SanitizeForSQL($str)
    {
        if( function_exists( "mysql_real_escape_string" ) )
        {
              $ret_str = mysql_real_escape_string( $str );
        }
        else
        {
              $ret_str = addslashes( $str );
        }
        return $ret_str;
    }
    
 /*
    Sanitize() function removes any potential threat from the
    data submitted. Prevents email injections or any other hacker attempts.
    if $remove_nl is true, newline chracters are removed from the input.
    */
    function Sanitize($str,$remove_nl=true)
    {
        $str = $this->StripSlashes($str);

        if($remove_nl)
        {
            $injections = array('/(\n+)/i',
                '/(\r+)/i',
                '/(\t+)/i',
                '/(%0A+)/i',
                '/(%0D+)/i',
                '/(%08+)/i',
                '/(%09+)/i'
                );
            $str = preg_replace($injections,'',$str);
        }

        return $str;
    }    
    function StripSlashes($str)
    {
        if(get_magic_quotes_gpc())
        {
            $str = stripslashes($str);
        }
        return $str;
    }

    function InitSMTP($host,$port,$useAuth, $authType,$username,$password, $realm, $secure,  $hello)
    {
    	$this->smtpHost  = $host;
    	$this->smtpPort = $port;
    	if($useAuth) {
    		$this->SmtpAuth = true;
	    	$this->smtpAuthType  = $authType;
	    	$this->smtpUsername  = $username;
	    	$this->smtpPassword = $password;
	    	$this->smtpRealm = $realm;
	    	$this->SmtpSecur = $secure;
	    	$this->smtpHelo = $hello;
    	}
    }
    
    function setWelcomeEmailParams($mailSubject,$fromAdd, $greetingUser, $body, $charset, $priority){
    	$this->wuserMailSubject = $mailSubject ;
    	$this->wuserFromAdd = $fromAdd ;
    	$this->wuserGreetingUser = $greetingUser ;
    	$this->wuserBody = $body ;
    	$this->wuserCharset = $charset ;
    	$this->wuserPriority = $priority;
    }
    
    
    function setAdminOnRegMail($mailSubject,$fromAdd,$toAdd, $body, $charset,  $priority){
    	$this->aorMailSubject = $mailSubject ;
    	$this->aorFromAdd = $fromAdd ;
    	$this->aorBody = $body ;
    	$this->aorCharset = $charset ;
    	$this->aorTOAdd = $toAdd;
    	$this->aorPriority = $priority;
    }
    
    function setAdminIntimationMail($mailSubject,$fromAdd,$toAdd, $body, $charset, $priority){
    	$this->aieMailSubject = $mailSubject ;
    	$this->aieFromAdd = $fromAdd ;
    	$this->aieBody = $body ;
    	$this->aieCharset = $charset ;
    	$this->aieTOAdd = $toAdd;
    	$this->aiePriority = $priority;
    }
    
    function setWelcomeConfirmationEmailParams($mailSubject,$fromAdd, $body, $charset,$priority){
    	$this->wconfuMailSubject = $mailSubject ;
    	$this->wconfuFromAdd = $fromAdd ;
    	$this->wconfuBody = $body ;
    	$this->wconfuCharset = $charset ;
    	$this->wconfuPriority = $priority;
    }
    
    function setNewPasswordEmailParams($mailSubject,$fromAdd, $body, $charset, $priority){
    	$this->snpMailSubject = $mailSubject ;
    	$this->snpFromAdd = $fromAdd ;
    	$this->snpBody = $body ;
    	$this->snpCharset = $charset ;
    	$this->snpPriority = $priority;
    }
    
    function setSendLinkPasswordEmailParams($mailSubject,$fromAdd, $body, $charset, $priority){
    	$this->slpMailSubject = $mailSubject ;
    	$this->slpFromAdd = $fromAdd ;
    	$this->slpBody = $body ;
    	$this->slpCharset = $charset ;
    	$this->slpPriority = $priority;
    }
    
    function setMailer(){
    	$mail = new PHPMailer($this,false);
    	$mail->IsSMTP(); // telling the class to use SMTP
    	$mail->SMTPDebug  = 0;                     // enables SMTP debug information (for testing)
    	// 1 = errors and messages
    	// 2 = messages only
    	
    	$mail->SMTPAuth   = $this->SmtpAuth;                  // enable SMTP authentication
    	$mail->SMTPSecure = $this->SmtpSecur;                 // sets the prefix to the servier
    	$mail->Host       = $this->smtpHost;      // sets GMAIL as the SMTP server
    	$mail->Port       = $this->smtpPort;                   // set the SMTP port for the GMAIL server
    	$mail->Username   = $this->smtpUsername;  // GMAIL username
    	$mail->Password   = $this->smtpPassword;            // GMAIL password
    	$mail->Helo 	  = $this->smtpHelo;
    	$mail->Realm      =  $this->smtpRealm;
     	$mail->AuthType = $this->smtpAuthType;

    	return $mail;
    }
    
}
?>